package com.cndw.kungfu.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.cndw.kungfu.comm.TeamInspection;
import com.cndw.kungfu.config.ConstantsChat;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.config.ConstantsTask;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Scene;
import com.cndw.kungfu.domain.Undercity;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.battle.Fighter;
import com.cndw.kungfu.model.battle.Team;
import com.cndw.kungfu.model.sys.ChatMain;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.kungfu.vo.ScenePlayerVO;
import com.cndw.kungfu.vo.battlevo.TeamCampVO;
import com.cndw.kungfu.vo.battlevo.TeamPlayerVO;
import com.cndw.kungfu.vo.battlevo.TeamVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 玩家组队
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2011-11-5 下午2:40:23
 */
@Controller
public class TeamController {
	
	/**
	 * 显示场景的队伍列表
	 * @param session
	 * @return
	 */
	public ResponseMessage show(Session session){
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
		if (scene == null) {
			return null;
		}
		Set<Long> currentIds = scene.getPlayerIds(player.getSubLine());
		List<ScenePlayerVO> playerList = new ArrayList<ScenePlayerVO>();
		int nums = 0;
		for (long scenePlayerId : currentIds) {
			Player currentPlayer = Context.getPlayerServer().getByPlayerId(scenePlayerId);
			if (currentPlayer.getTeamId() > 0 ) {
				Team team = currentPlayer.getTeam();
				if (team != null && team.isMaster(scenePlayerId)) {
					playerList.add(currentPlayer.toScenePlayerVO());
					nums++;
					if (nums >= 16) {
						break;
					}
				}
			}			
		}		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("playerList", playerList);		
		return ResponseMessage.getSuccMessage(map);
	}
	

	/**
	 * 创建队伍
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage create(Session session) {
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getTeam() != null) {
			return null;
		}
		if (!TeamInspection.checkControl(player)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.control"));
		}		
		Team team = new Team(player);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("teamId", team.getId());
		
		Context.getTaskServer().notifyToSpark(playerId, ConstantsTask.spark13TeamAdd, 1);
		
		return ResponseMessage.getSuccMessage(map);
	}
	
	public ResponseMessage crateByUnderId(Session session,int underId){
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getTeam() != null) {
			return null;
		}
		if (!TeamInspection.checkControl(player)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.control"));
		}		
		Team team = new Team(player);
		team.setSignUnderId(underId);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("teamId", team.getId());
		Undercity undercity = Context.getUndercityServer().getUndercity(underId);
		if (undercity != null) {
			String message = LanguageLib.get("team.create.suc",undercity.getLevel(),undercity.getName(),playerId);
			ChatMain.commMessage(player, message,ConstantsChat.xtTeam,playerId);
		}
		
		Context.getTaskServer().notifyToSpark(playerId, ConstantsTask.spark13TeamAdd, 1);
		
		return ResponseMessage.getSuccMessage(map);
	}
	
	public ResponseMessage createByType(Session session,int type){
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getTeam() != null) {
			return null;
		}
		if (!TeamInspection.checkControl(player)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.control"));
		}		
		Team team = new Team(player);
		team.setType(type);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("teamId", team.getId());
		if (type == 1) {
			String message = LanguageLib.get("team.create.campcross",session.getUid());
			ChatMain.commMessage(player, message,ConstantsChat.xtTeam,session.getUid());
		}
		
		return ResponseMessage.getSuccMessage(map);
		
	}
	
	
	public ResponseMessage list(Session session,int underId){
		Collection<Team> teams = Context.getDataServer().getTeams();
		List<TeamVO> list = new ArrayList<TeamVO>();
		for (Team team : teams) {
			if (team.getSignUnderId() == 0) {
				continue;
			}
			if (!Context.getPlayerServer().isOnline(team.getMaster().getUniqueId())) {
				continue;
			}
			if (underId > 0 && team.getSignUnderId() != underId) {
				continue;
			}
			if (team.getUndercity() != null) {
				continue;
			}
			TeamVO e = new TeamVO();
			e.setPlayerId(team.getMaster().getUniqueId());
			e.setPlayerName(team.getMaster().getName());
			e.setUnderId(team.getSignUnderId());
			
			Undercity undercity = Context.getUndercityServer().getUndercity(team.getSignUnderId());
			e.setUnderLevel(undercity.getLevel());
			e.setUnderName(undercity.getName());
			List<Object> members = new ArrayList<Object>();
			for (Player player : team.getAllPlayers()) {
				members.add(new Object[]{player.getPlayerId(),player.getPlayerName(),player.getLevel(),player.getVocationId()});
			}
			e.setMembers(members);
			list.add(e);
			
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);		
		return ResponseMessage.getSuccMessage(map);
	}

	
	public ResponseMessage listByType(Session session,int type){
		Collection<Team> teams = Context.getDataServer().getTeams();
		List<TeamCampVO> list = new ArrayList<TeamCampVO>();
		for (Team team : teams) {
			if (team.getType() == 0) {
				continue;
			}
			if (!Context.getPlayerServer().isOnline(team.getMaster().getUniqueId())) {
				continue;
			}
			if (type > 0 && team.getType()!= type) {
				continue;
			}
			TeamCampVO e = new TeamCampVO();
			e.setPlayerId(team.getMaster().getUniqueId());
			e.setPlayerName(team.getMaster().getName());
			List<Object> members = new ArrayList<Object>();
			for (Player player : team.getAllPlayers()) {
				members.add(new Object[]{player.getPlayerId(),player.getPlayerName(),player.getLevel(),player.getVocationId()});
			}
			e.setMembers(members);
			list.add(e);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);		
		return ResponseMessage.getSuccMessage(map);
	}	
	/**
	 * 邀请入队
	 * 
	 * @param session
	 * @param playerId
	 * @return
	 */
	public ResponseMessage invite(Session session, long targetId) {
		if (targetId == session.getUid() ) {
			return null;
		}
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (!TeamInspection.checkControl(player)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.control"));
		}
		if (player.getTeam() != null) {
			Team team = player.getTeam();
			if (team.getMaster().getUniqueId() != playerId) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("team.invite.errmaster"));
			} else if (team.getMembers().size() >= Team.maxMemberSize) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("team.invite.errsize"));
			}else if (team.getUndercity() != null) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.undercity"));
			}
		}
		Player target = Context.getPlayerServer().getByPlayerId(targetId);
		if (!TeamInspection.checkControl(target)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.controlother"));
		}
		if (target.getTeam() != null ) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.invite.errhaved"));
		}
		player.getDataInfo().addTeamInvite(targetId);

		String title = LanguageLib.get("team.invite.message", player.getPlayerName(),player.getLevel());

		Context.getTcpServer().broadcastConfirm(title, "TeamController", "processInvite", 3, new Object[] { playerId }, targetId);

		return null;
	}

	/**
	 * 处理邀请
	 * 
	 * @param session
	 * @param playerId
	 * @return
	 */
	public ResponseMessage processInvite(Session session, long masterId, boolean agree) {
		long playerId = session.getUid();
		Player masterPlayer = Context.getPlayerServer().getByPlayerId(masterId);
		Player player = Context.getPlayerServer().getByPlayerId(playerId);

		if (masterPlayer == null) {
			return null;
		}
		if (masterPlayer.getDataInfo().isTeamInvite(playerId) == false) {
			return null;
		}
		masterPlayer.getDataInfo().removeTeamInvite(playerId);
		if (!agree) {
			String title = LanguageLib.get("team.invite.notagree",player.getPlayerName());
			Context.getTcpServer().broadcastResMsg(ResponseMessage.ticpErrMsg(title), masterId);
			return null;
		}
		if (!TeamInspection.checkControl(player)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.control"));
		}
		if (!TeamInspection.checkControl(masterPlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.controlother"));
		}		
		if (player.getTeamId() > 0) {
			return null;
		}
		Team team = masterPlayer.getTeam();
		if (team == null) {
			team = new Team(masterPlayer);
			Context.getTaskServer().notifyToSpark(masterId, ConstantsTask.spark13TeamAdd, 1);
		} else if (team.getMembers().size() >= Team.maxMemberSize) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.errsize"));
		}
		
		EventNotice notice = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamAdd);		
		notice.comitData(player.toTeamPlayerVO());
		notice.broadcast(team.getMemberIds());		
		
		team.memberAdd(player);
		Context.getTaskServer().notifyToSpark(playerId, ConstantsTask.spark13TeamAdd, 1);
		
		List<TeamPlayerVO> members = new ArrayList<TeamPlayerVO>();
		EventNotice noticeMembers = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamMembers);		
		for (Fighter e : team.getMembers()) {
			if (e.getUniqueId() != playerId) {
				Player player2 = Context.getPlayerServer().getByPlayerId(e.getUniqueId());
				members.add(player2.toTeamPlayerVO());
			}
		}
		noticeMembers.comitData(members);
		noticeMembers.put("masterId",team.getMaster().getUniqueId());
		noticeMembers.put("underId",team.getSignUnderId());
		
		noticeMembers.broadcast(playerId);
		
		return null;
	}

	/**
	 *  申请加入某个玩家的队伍
	 * @param session
	 * @param masterId
	 * @return
	 */
	public ResponseMessage apply(Session session, long masterId) {
		long playerId = session.getUid();
		if (masterId == playerId) {
			return null;
		}
		Player masterPlayer = Context.getPlayerServer().getByPlayerId(masterId);
		if (masterPlayer == null) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getTeamId() > 0) {
			return null;
		}
		if (!TeamInspection.checkControl(player)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.control"));
		}		
		if (!TeamInspection.checkControl(masterPlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.controlother"));
		}	
		Team team = masterPlayer.getTeam();
		if (team == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.noteam"));
		}else if (team.getMembers().size() >= Team.maxMemberSize) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.errsize"));
		}else if (team.applyContains(playerId)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.haved"));
		}else if (team.getUndercity() != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.undercity"));
		}
		if (team.getSignUnderId() > 0 ) {
			Undercity undercity = Context.getUndercityServer().getUndercity(team.getSignUnderId());
			if (undercity!= null) {
				if ( undercity.getLevel() > player.getLevel() || undercity.getLevelMax() < player.getLevel()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.level",undercity.getName(),undercity.getLevel(),undercity.getLevelMax()));
				}
				if (undercity.getTimes() <= player.getDataInfo().getEveryDay().getUndercityTimes(team.getSignUnderId())) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.times",undercity.getName()));
				}
			}	
		}else if (team.getType() == 1) {
			if (player.getLevel() < ConstantsLevel.lv70CampCross) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.leveltype",ConstantsLevel.lv70CampCross));
			}
		}
		
		
		team.applyAdd(playerId);
		String title = LanguageLib.get("team.apply.title",player.getPlayerName(),player.getLevel());
		Context.getTcpServer().broadcastConfirm(title, "TeamController", "processApply", 3, new Object[] { playerId }, team.getMaster().getUniqueId());

		

		return ResponseMessage.ticpMsg(LanguageLib.get("team.apply.suc"));
	}

	/**
	 * 通过申请
	 * @param session
	 * @param memberId
	 * @param agree
	 * @return
	 */
	public ResponseMessage processApply(Session session,long memberId,boolean agree) {
		
		long playerId = session.getUid();
		Player masterPlayer = Context.getPlayerServer().getByPlayerId(playerId);
		if (masterPlayer == null) {
			return null;
		}
		Team team = masterPlayer.getTeam();
		if (team == null) {
			return null;
		}else if (team.applyContains(memberId) == false) {
			return null;
		}
		team.applyRemove(memberId);
		Player memberPlayer = Context.getPlayerServer().getByPlayerId(memberId);

		if (!agree) {
			String title = LanguageLib.get("team.apply.notagree",masterPlayer.getPlayerName());
			Context.getTcpServer().broadcastResMsg(ResponseMessage.ticpErrMsg(title), memberId);
			return null;
		}	
		if (!TeamInspection.checkControl(masterPlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.control"));
		}		
		if (!TeamInspection.checkControl(memberPlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.controlother"));
		}		
		if (memberPlayer.getTeamId() > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.apply.other"));
		}
		if (team.getMembers().size() >= Team.maxMemberSize) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.invite.errsize"));
		}
		EventNotice notice = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamAdd);		
		notice.comitData(memberPlayer.toTeamPlayerVO());
		notice.broadcast(team.getMemberIds());		
		
		team.memberAdd(memberPlayer);
		Context.getTaskServer().notifyToSpark(memberId, ConstantsTask.spark13TeamAdd, 1);
		
		List<TeamPlayerVO> members = new ArrayList<TeamPlayerVO>();
		EventNotice noticeMembers = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamMembers);		
		for (Fighter e : team.getMembers()) {
			if (e.getUniqueId() != memberId) {
				Player player2 = Context.getPlayerServer().getByPlayerId(e.getUniqueId());
				members.add(player2.toTeamPlayerVO());
			}
		}
		noticeMembers.put("masterId",team.getMaster().getUniqueId());
		noticeMembers.put("underId",team.getSignUnderId());
		noticeMembers.comitData(members);
		noticeMembers.broadcast(memberId);
			
	
		return null;
	}
	/**
	 * 退出队伍
	 * @param session
	 * @return
	 */
	public ResponseMessage exit(Session session){
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Team team = player.getTeam();
		if (team == null) {
			return null;
		}else if (team.getUndercity() != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.undercity"));
		}
		team.memberRemove(player);

		return ResponseMessage.getSuccMessage(true);
	}
	/**
	 * 驱逐出队伍
	 * @param session
	 * @param memberId
	 * @return
	 */
	public ResponseMessage expel(Session session,long memberId){
		if (memberId == session.getUid()) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Team team = player.getTeam();
		if (team == null) {
			return null;
		}
		if (team.getMaster().getUniqueId() != player.getPlayerId()) {
			return null;
		}else if (team.getUndercity() != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.undercity"));
		}
		Player memberPlayer = Context.getPlayerServer().getByPlayerId(memberId);
		if (memberPlayer == null) {
			return null;
		}
		
		team.memberRemove(memberPlayer);	
		
		EventNotice notice = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamExpel);
		notice.comitData(LanguageLib.get("team.exit.expel"));
		notice.broadcast(memberId);
		
		return null;
	}
	/**
	 * 解散
	 * @param session
	 * @return
	 */
	public ResponseMessage dissolve(Session session){
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Team team = player.getTeam();
		if (team == null) {
			return null;
		}
		if (team.getMaster().getUniqueId() != player.getPlayerId()) {
			return null;
		}
		if (team.getUndercity() != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.undercity"));
		}		
		for (long memberId : team.getMemberIds()) {
			Player memberPlayer = Context.getPlayerServer().getByPlayerId(memberId);
			memberPlayer.setTeamId(0);
		}
		
		EventNotice notice = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamExpel);
		notice.comitData(LanguageLib.get("team.exit.dissolve"));
		for (long memberId : team.getMemberIds()) {
			if (memberId != player.getPlayerId()) {				
				notice.broadcast(memberId);
			}
		}
		Context.getDataServer().teamRemove(team.getId());
		return ResponseMessage.getSuccMessage(true);
	}
	
	/**
	 * 转让队长
	 * @param session
	 * @param masterId
	 * @return
	 */
	public ResponseMessage entrustMaster(Session session,long masterId){
		if (session.getUid() == masterId) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Team team = player.getTeam();
		if (team == null || team.getMaster().getUniqueId() != session.getUid()) {
			return null;
		}
		if (team.containsUniqueId(masterId) == false) {//不存在的队员
			return null;
		}
		team.setMaster(team.getFighter(masterId));
		team.upPCManster();
		
		EventNotice notice = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamEntrust);
		notice.put("masterId",masterId);
		notice.broadcast(team.getMemberIds());
		
		return ResponseMessage.getSuccMessage(true);
	}
	
	
}
